/* eslint-disable */
import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken } from "@/utils/auth"; // get token from cookie
import getPageTitle from "@/utils/get-page-title";
import nProgress from "nprogress";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

// 白名单设置
const whileList = ["/login", "/auth-redirect", "/home"];

// 挂载路由导航守卫：to表示将要访问的路径，from表示从哪里来，next是下一个要做的操作
router.beforeEach((to, from, next) => {
  // progress bar start
  NProgress.start();

  document.title = getPageTitle(to.meta.title);

  // determine has login in
  const hasToken = getToken();

  if (hasToken) {
    // 放行登录页面
    if (to.path === "/login") {
      next();
      NProgress.done();
    } else {
      // get user info
      try {
        // login use creat route about permission role

        // hack method to ensure that addRoutes is complete
        // set the replace: true, so the navigation will not leave a history record
        next({ ...to, replace: true });
      } catch (error) {
        // remove token and go to login page to re-login
        //   await store.dispatch('user/resetToken')
        Message.error(error || "Has Error");
        next(`/login?redirect=${to.path}`);
        NProgress.done();
      }
    }
  } else {
    // has no token
    if (whileList.indexOf(to.path) !== -1) {
      // whilte list pass
      next();
    } else {
      // other no login page redirected to login page
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

// finish
router.afterEach(() => {
  NProgress.done();
});
